<template>
  <div class="chat-body">
    <!-- 对话框 -->
    <div v-for="(msg, msgIndex) in msgList" :key="msg.data.questionId" class="chat-item">
      <div v-if="msg.type == 'robot'" class="robot-body">
        <img src="@/assets/images/robot.png" alt="图片加载失败" class="profile">
        <!-- 欢迎语 -->
        <div v-if="msg.flag == 1" class="welcome chat-text">
          <div class="h1">Hi, 我是您的智能助手-<span class="blue">智明矿通</span></div>
          <div class="msg-content">{{ msg.data.answer }}</div>
        </div>
        <!-- 机器人回答  -->
        <div v-else-if="msg.flag == 2" class="answer chat-text">
          <div v-if="msg.data.answer.length == 0">
            <svg-icon iconClass="loading" class="loadingIcon" />
            理解问题
          </div>
          <template v-else>
            <div class="answer-body">
              <div v-html="setHtml(msg)" class="answer-content"></div>
              <div class="loadingIconReal">
                <svg-icon v-show="!msg.isover" iconClass="loading" class="icon" />
              </div>
            </div>
          </template>
          <div v-if="msg.data.sources.length" class="source-body">
            <div class="source-switch" :class="{ active: sourceCut }" @click="handleSource">
              <svg-icon iconClass="magnifier" />
              <span>搜索到{{ msg.data.sources.length }}条数据源</span>
              <el-icon>
                <ArrowDownBold />
              </el-icon>
            </div>
            <div class="source-scroll" :class="sourceCut ? 'sourceOpen' : 'sourceClose'">
              <div @click="handleScroll(1)" class="icon-left">
                <el-icon>
                  <ArrowLeftBold />
                </el-icon>
              </div>
              <div @click="handleScroll(2)" class="icon-right">
                <el-icon>
                  <ArrowRightBold />
                </el-icon>
              </div>
              <div v-for="(item, index) in msg.data.sources" :key="item.id" @click="handleLink(item)"
                class="source-item">
                <div v-html="index + 1 + '.' + item.title"></div>
              </div>
            </div>
          </div>
          <el-button v-if="msg.data.answer.length != 0" type="primary" link :icon="Refresh"
            @click="handleRefresh(msgIndex)" class="refresh">重新生成</el-button>
        </div>
        <el-button v-if="msgIndex == msgList.length - 1 && msg.flag !== 1 && !msg.isover" type="primary" plain
          @click="handleStop" class="stop">
          <svg-icon iconClass="stop" />
          停止生成
        </el-button>

        <!-- 每次对话下面的推荐问题 -->
        <div v-if="msg.recom" class="recommend">
          <div v-for="(item, index) in recomList" :key="index" @click="handleRecommend(item)" class="recom-item">
            <TooltipView :value="item" />
            <el-icon>
              <ArrowRight />
            </el-icon>
          </div>
        </div>
      </div>
      <div v-else-if="msg.type == 'user'" class="user-body">
        <img :src="userAcatar" alt="图片加载失败" class="profile user">
        <div class="chat-text user-text">
          {{ msg.data.answer }}
        </div>
      </div>
    </div>
  </div>
  <!-- 底部输入框 -->
  <div class="msg-input">
    <el-button v-if="msgList.length > 0 && msgList[0].type == 'user'" type="default" plain
      class="reset-btn black black-border" @click="handleResetMsg">
      <svg-icon iconClass="duihua" />
      新建对话
    </el-button>
    <el-input ref="userMessageRef" v-model="userMessageText" :rows="6" resize="none" type="textarea"
      placeholder="输入你的问题, 通过shift+回车换行" @keydown="handleEnter">
    </el-input>
    <div class="msg-btn">
      <el-button circle plain :disabled="userMessageText.length == 0" @click="handleReset">
        <svg-icon iconClass="clear" />
      </el-button>
      <el-button type="primary" circle :disabled="userMessageText.length == 0" @click="handleEnter(false)">
        <svg-icon iconClass="send" />
      </el-button>
    </div>
    <div class="footer-txt">以上内容均由AI大模型生成，仅供参考和借鉴</div>
  </div>
</template>

<script lang="ts" setup>
import {
  nextTick, ref, watch, onActivated, onDeactivated
} from "vue";
import { chartStor } from "@/store/chart";
import { Refresh } from '@element-plus/icons-vue';
import { uuid } from "@/utils/randomNumber";
import { marked } from "marked";
const { initChat, setChat, closeChat } = chartStor();

const props = defineProps({
  // 用户头像
  userAcatar: {
    required: true,
    type: String,
    default: "",
  }
});

onActivated(() => {
  initChat("/qa");
});
onDeactivated(() => {
  // 关闭链接
  closeChat();
});
let userAcatar = ref<string>("");
requestAnimationFrame(() => {
  userAcatar.value = JSON.parse(sessionStorage.getItem("userInfo"))?.avatar;
});
watch(() => props.userAcatar, (newV) => {
  userAcatar.value = newV;
});

/**
 * @sessionId : 会话唯一ID(新建会话或者打开新页签后sessionId会变化)
 * @type : robot(机器人) user(用户)
 * @flag : 1(欢迎语)
 * @recom : 当前回答是否展示推荐问题
 * @isover : 是否回答完毕
 * @data .answer : 文本回答
 * @data .sources : 数据源
 * @data .questionId : 每个问题唯一ID，根据此ID判断是哪一个问题的回答问题
 * @data .timestamp : 时间戳
 */
let msgList = ref<Array<any>>([{
  sessionId: 1,
  type: "robot",
  flag: 1,
  isover: true,
  recom: true,
  data: {
    answer: "基于海量数据记忆、高效算力和自然对话能力，我可以回答您关于矿山政策、行业标准等专业知识，希望能让您的工作更加高效、便捷。",
    sources: "",
    questionId: "",
    timestamp: "",
  }
}]);
let recomList = ref<Array<any>>(["近5年，国家出台了哪些矿山安全政策？", "关于深入推进矿山智能化建设促进矿山安全发展的指导意见，如何解读？", "近5年，国家出台了哪些国家都有哪些矿山标准规范？矿山安全政策？"])
// 数据源
let sourceCut = ref<boolean>(false);
function handleSource() {
  sourceCut.value = !sourceCut.value;
}
// 数据左右箭头点击
function handleScroll(type) {
  const scrollBody = document.querySelector(".source-scroll");
  // const scrollClientRects = scrollBody.getClientRects()
  const scrollWidth = scrollBody.scrollWidth;
  const scrollLeft = scrollBody.scrollLeft;
  if (type == 1) {
    if (scrollLeft == 0) {
      scrollBody.scrollLeft = 0;
    } else {
      scrollBody.scrollLeft -= 40;
    }
  } else if (type == 2) {
    if (scrollLeft >= (scrollWidth - scrollBody.clientWidth)) {
      scrollBody.scrollLeft = scrollWidth - scrollBody.clientWidth;
    } else {
      scrollBody.scrollLeft += 40;
    }
  }
}
// 推荐问题点击
function handleRecommend(item) {
  userMessageText.value = item;
  userMessageRef.value.focus();
}
let userMessageRef = ref(null);
let userMessageText = ref<string>("");
// 发送消息
// 会话唯一id, 没打开一个页签都会生成一个唯一id
const sessionId = ref<string>(uuid());
function handleEnter(e) {
  requestAnimationFrame(() => {
    if (!userMessageText.value.length || (msgList.value.length > 0 && !msgList.value[msgList.value.length - 1].isover)) {
      return false;
    }
    if (e.keyCode == 13 && !e.shiftKey) {
      // 按下回车且没按shift键
      // 去除欢迎语
      if (msgList.value.length && msgList.value[0].flag == 1 && msgList.value[0].type == "robot") {
        msgList.value.splice(0, 1);
      }
      e.preventDefault();
      // 每个问题唯一ID，根据此ID判断是哪一个问题的回答
      const questionId = uuid();
      msgList.value.push({
        sessionId: sessionId.value,
        type: "user",
        flag: 1,
        data: {
          answer: userMessageText.value.replace(/\s/g, ""),
          questionId: "user:" + questionId,
          timestamp: "",
        }
      });
      // 请求接口,在回答前先插入一条加载中的空数据
      msgList.value.push({
        sessionId: sessionId.value,
        type: "robot",
        flag: 2,
        isover: false,
        recom: false,
        data: {
          answer: "",
          sources: "",
          questionId: questionId,
          timestamp: "",
        }
      });
      const params = {
        sessionId: sessionId.value,
        questionId: questionId,
        userMessageText: userMessageText.value,
        callBack
      }
      setChat(params);
      userMessageText.value = "";
    } else if (!e) {
      // 按下发送按钮
      // 去除欢迎语
      if (msgList.value.length && msgList.value[0].flag == 1 && msgList.value[0].type == "robot") {
        msgList.value = msgList.value.slice(1);
      }
      // 每个问题唯一ID，根据此ID判断是哪一个问题的回答
      const questionId = uuid();
      msgList.value.push({
        sessionId: sessionId.value,
        type: "user",
        flag: 1,
        data: {
          answer: userMessageText.value.replace(/\s/g, ""),
          questionId: "user:" + questionId,
          timestamp: "",
        }
      });
      // 请求接口,在回答前先插入一条加载中的空数据
      msgList.value.push({
        sessionId: sessionId.value,
        type: "robot",
        flag: 2,
        isover: false,
        recom: false,
        data: {
          answer: "",
          sources: "",
          questionId: questionId,
          timestamp: "",
        }
      });
      const params = {
        sessionId: sessionId.value,
        questionId: questionId,
        userMessageText: userMessageText.value,
        callBack
      }
      setChat(params);
      userMessageText.value = "";
    }
    scrollToBtm();
  })
}
// 数据源跳转
function handleLink(item) {
  window.open(item.source);
}
// 滚动到底部
function scrollToBtm() {
  nextTick(() => {
    // 每次滚动到最下面
    const scrollBox = document.querySelector(".chat-body");
    scrollBox.scrollTo({
      top: scrollBox.scrollHeight,
      behavior: 'smooth' // 可选，平滑滚动效果
    });
  });
}
// 重新生成
function handleRefresh(index) {
  userMessageText.value = msgList.value[index - 1].data.answer;
  msgList.value.splice(index, 1);
  msgList.value.splice(index - 1, 1);
  handleEnter(false);
}
// 停止生成
function handleStop() {

}
// 回调函数接受返回值
function callBack(val, msg) {
  // console.log("接收到了", val);
  if (msg == "error") {
    // 连接超时, 清除未接收完的信息
    msgList.value = msgList.value.filter((item, index) => {
      return (item.isover == true || (item.type == "user" && index < msgList.value.length - 2));
    });
    return false;
  }
  const { data, type, sessionId } = val;
  if (type == "reply") {
    const robotList = msgList.value.filter(item => {
      return item.type == "robot";
    })
    robotList.forEach((item, index) => {
      if (item.type == "robot" && item.data.questionId == data.questionId) {
        item.isover = false;
        item.data.answer += data.answer;

        // item.data.answer = marked(`在煤矿场景下，大模型的应用主要集中在提升安全生产、优化管理以及智能化升级方面。以下是一些典型的大模型应用场景：

        // 1. **综采面智能放顶煤**：
        //    - 利用视频、声音和煤层厚度等因子进行综合分析，实现对综采工作面的精准控制。
        //    - **应用技术包括**：全景视频拼接、滚筒与护帮板防碰撞检测、煤壁片帮识别及刮板输送机堆煤识别。

        // 2. **安全监控系统**：
        //    - 通过大模型进行烟火检测、吸烟检测、安全帽检测以及人员动作分析。
        //    - 监控员工是否规范佩戴安全设备，防止不合规的操作行为，并且能够及时发现可能存在的安全隐患。

        // 3. **危险区域监控**：
        //    - 预警和预防误入危险区域，通过大模型判断人员的行为是否偏离了规定路线或操作范围。

        // 4. **关键岗位状态监护**：
        //    - 对于重要岗位的工作状态进行实时监测，确保员工在岗且工作状态正常。

        // 5. **煤矿限员管理**：
        //    - 使用大模型实现对煤矿现场人数的准确计数和限制，防止超员现象发生。

        // 6. **规范作业执行**：
        //    - 通过分析人员行为数据，识别是否遵循安全操作规程，从而提高作业过程中的安全性。

        // 这些应用不仅有助于提升煤矿生产效率，更关键的是能够显著增强安全生产水平。通过引入AI大模型的概念和平台技术积累，可以降低人工智能的开发门槛，并缩短模型训练周期，实现人工智能的“工业化开发模式”。

        // 具体到某一款产品或服务，比如星火认知大模型V4.0(参考链接：<a>https://xinghuo.xfyun.cn/</a>)，在实际应用中展现了其在烟火检测、煤矿限员管理、人员动作分析、误入安全区域预警及关键岗位状态监护等方面的良好泛化能力。`);
        item.questionId = data.questionId;
        item.timestamp = data.timestamp;
      }
    });
  } else if (type == "dataSource") {
    // 数据源
    msgList.value.forEach(item => {
      if (item.type == "robot" && item.data.questionId == data.questionId) {
        item.data.sources = data.sources;
        item.isover = true;
      }
    });
  } else if (type == "recommendQuestion") {
    // 推荐问题
    recomList.value = data.questions;
    msgList.value.forEach((item, index) => {
      if (index == msgList.value.length - 1) {
        item.recom = true;
      } else {
        item.recom = false;
      }
    });
  }
  scrollToBtm()
}
// 将富文本解析成html
function setHtml(item) {
  if (!item.data.answer) {
    return false
  }
  const htmlString: any = marked(item.data.answer);
  const robotList = msgList.value.filter(msg => {
    return msg.type == "robot";
  });
  let robotIndex = null;
  robotList.forEach((msg, index) => {
    if (msg.data.questionId == item.data.questionId && !item.isover) {
      robotIndex = index;
    }
  })
  if (robotIndex !== null) {
    nextTick(() => {
      const dom = document.querySelectorAll(".answer-content")[robotIndex];
      const loadingIcon: any = document.querySelectorAll(".loadingIconReal")[robotIndex];
      if (!!dom) {
        const lastTextNode = getLastTextNode(dom);
        // 在最后一个文本节点加文字
        const tempNode = document.createTextNode('|');
        if (lastTextNode) {
          lastTextNode.parentNode.insertBefore(tempNode, lastTextNode.nextSibling);
        } else {
          dom.appendChild(tempNode);
        }

        //根据文本节点设置光标位置
        const range = document.createRange();
        //选中文本对象
        range.setStart(tempNode, 0);
        range.setEnd(tempNode, 0);

        // 获取相对视口位置
        const rect = range.getBoundingClientRect();
        // 获取容器相对视口位置
        const containerRect = dom.getBoundingClientRect();

        const x = rect.left - containerRect.left;
        const y = rect.top - containerRect.top;
        if (!!loadingIcon) {
          // loadingIcon.style.left = x + "px";
          // loadingIcon.style.top = y - 5 + "px";
          loadingIcon.style.transform = `translate(${x}px, ${y}px)`;
        }
        tempNode.remove();
      }
    });
  }
  return htmlString;
}
// 获取最后一个文本节点
function getLastTextNode(node) {
  if (node.nodeType === Node.TEXT_NODE && node.data != "\n") {
    return node;
  }
  let childNodes = node.childNodes;
  for (let i = childNodes.length - 1; i >= 0; i--) {
    let lastTextNode = getLastTextNode(childNodes[i]);
    if (lastTextNode) {
      return lastTextNode;
    }
  }
  return null;
}



// 新建对话
function handleResetMsg() {
  msgList.value = [{
    sessionId: 1,
    type: "robot",
    flag: 1,
    isover: true,
    recom: true,
    data: {
      answer: "基于海量数据记忆、高效算力和自然对话能力，我可以回答您关于矿山政策、行业标准等专业知识，希望能让您的工作更加高效、便捷。",
      sources: "",
      questionId: "",
      timestamp: "",
    }
  }];
  sessionId.value = uuid();
}
// 输入框重置
function handleReset() {
  userMessageText.value = "";
}

</script>

<style lang="scss" scoped>
.chat-body {
  height: calc(100% - 350px);
  margin-top: 53px;
  font-family: PingFang SC, PingFang SC-Regular;
  padding-right: 18.2vw;
  margin-bottom: 10px;
  overflow-y: auto;


  .chat-item {
    .chat-text {
      width: calc(100% - 55px);
    }

    .profile {
      width: 36px;
      height: 36px;
      margin-right: 15px;

      &.user {
        border-radius: 50%;
      }
    }

    .robot-body {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      margin-top: 20px;

      .welcome {

        .h1 {
          line-height: 24px;
          font-size: 24px;
          font-family: PingFang SC, PingFang SC-Medium;
          font-weight: 600;
          text-align: left;
          color: #1a202c;
        }

        .msg-content {
          font-size: 16px;
          font-weight: 400;
          text-align: left;
          color: #1a202c;
          margin-top: 10px;
        }
      }

      :deep(ol) {
        padding-left: 26px;
      }

      .answer {
        background: #ffffff;
        border: 1px solid #d4d5db;
        border-radius: 16px;
        box-shadow: 0px 2px 14px 0px rgba(0, 0, 0, 0.06);
        padding: 24px 32px;
        font-family: PingFang SC, PingFang SC-Regular;
        font-size: 16px;
        font-weight: 400;
        text-align: left;
        color: #292929;

        .loadingIcon {
          color: #2D65F7;
          animation: circle 1s infinite;
        }

        .answer-body {
          position: relative;
          display: flex;

          .loadingIconReal {
            position: absolute;
          }

          .loadingIconReal {
            .icon {
              color: #2D65F7;
              animation: circle 1s infinite;
            }
          }
        }


        .source-body {
          position: relative;
          width: 100%;
          margin: 12px 0;
          user-select: none;

          .source-switch {
            width: 188px;
            height: 40px;
            line-height: 40px;
            background: #f6f7f9;
            cursor: pointer;
            text-align: center;
            border-radius: 8px;

            &:hover {
              background: #F2F2F2;
            }

            &.active {
              .el-icon {
                transform: rotate(180deg);
              }
            }

            >span {
              font-size: 14px;
              font-family: PingFang SC, PingFang SC-Medium;
              font-weight: 600;
              text-align: left;
              color: #292929;
            }

            .el-icon {
              color: #000000;
              vertical-align: middle;
              margin-left: 8.75px;
            }

          }

          .source-scroll {
            display: flex;
            justify-content: flex-start;
            flex-wrap: nowrap;
            width: 100%;
            background: #f6f7f9;
            border-radius: 8px;
            padding: 16px 0;
            overflow-x: auto;
            overflow-y: hidden;
            margin-top: 10px;
            font-size: 13px;
            box-sizing: border-box;

            &.sourceOpen {
              height: 124px;
              transition: .3s;
            }

            &.sourceClose {
              height: 0;
              padding: 0;
              transition: .3s;
              overflow: hidden;

              .icon-left,
              .icon-right {
                display: none;
              }
            }

            .icon-left,
            .icon-right {
              position: absolute;
              top: calc(50% + 26px);
              transform: translateY(-50%);
              width: 24px;
              height: 24px;
              line-height: 24px;
              background: #fff;
              border-radius: 50%;
              border: 1px solid #f6f7f9;
              box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.20);
              color: #292929;
              text-align: center;
              cursor: pointer;

              &:hover {
                color: #2D65F7;
              }

              .el-icon {
                font-size: 14px;
              }
            }

            .icon-left {
              left: -12px;
            }

            .icon-right {
              right: -12px;
            }

            .source-item {
              min-width: 272px;
              max-width: 272px;
              height: 100%;
              margin: 0 12px;
              background: #ffffff;
              border: 1px solid rgba(151, 151, 151, 0.20);
              border-radius: 6px;
              padding: 14px;
              cursor: pointer;

              &:hover {
                background: rgba(242, 242, 242, 0.40);
                border: 1px solid rgba(151, 151, 151, 0.20);
                box-shadow: 0px 2px 14px 0px rgba(0, 0, 0, 0.06);
              }

              >div {
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 3;
                overflow: hidden;
                text-overflow: ellipsis;
              }

            }
          }
        }

        .refresh {
          margin-top: 10px;
          margin-left: -10px;
          width: 100px;
          height: 32px;

          &:hover {
            color: #2D65F7;
            background: #f6f7f9;
          }
        }
      }

      .stop {
        margin: 10px 0 0 50px;
        border-radius: 8px;
      }
    }

    .recommend {
      width: 100%;

      .recom-item {
        display: flex;
        align-items: center;
        max-width: calc(100% - 50px);
        width: fit-content;
        height: 40px;
        line-height: 40px;
        background: #ffffff;
        border: 1px solid #d4d5db;
        border-radius: 10px;
        box-shadow: 0px 2px 14px 0px rgba(0, 0, 0, 0.06);
        font-size: 16px;
        font-weight: 400;
        padding: 0 10px;
        margin: 10px 0 10px 50px;
        cursor: pointer;
        user-select: none;
        font-size: 16px;
        font-family: PingFang SC, PingFang SC-Regular;
        font-weight: 400;
        text-align: justify;
        color: #292929;

        &:nth-child(1) {
          margin-top: 20px;
        }

        &:hover {
          background: rgba(242, 242, 242, 0.40);
          border: 1px solid #d4d5db;
          border-radius: 10px;
          box-shadow: 0px 2px 14px 0px rgba(0, 0, 0, 0.11);
        }

        :deep(ol) {
          padding-left: 0;

          li {
            list-style: none;
          }
        }
      }
    }

    .user-body {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      margin-top: 20px;

      .user-text {
        font-family: inherit;
        padding: 6px 0;
        font-size: 16px;
        font-weight: 400;
        text-align: left;
        color: #292929;
      }
    }
  }
}

.msg-input {
  position: relative;
  font-family: PingFang SC, PingFang SC-Regular;
  padding-right: 18.2vw;

  .reset-btn {
    border-radius: 11px;
    box-shadow: 0px 2px 16px 0px rgba(0, 0, 0, 0.06);
    margin-bottom: 12px;

    .svg-icon {
      transform: rotateY(180deg);
      font-size: 20px;
    }
  }

  :deep(.el-textarea) {
    border-radius: 16px;
    box-shadow: 0px 2px 16px 0px rgba(0, 0, 0, 0.11);

    .el-textarea__inner {
      border-radius: 16px;
      color: #292929;
      padding: 11px;
    }
  }

  .footer-txt {
    font-size: 14px;
    font-weight: 400;
    text-align: left;
    color: #8d949e;
    margin-top: 16px;
  }

  .msg-btn {
    position: absolute;
    right: calc(18.2vw + 20px);
    bottom: 45px;

    .svg-icon {
      margin-right: 0;
      font-size: 17px;
    }
  }
}

@keyframes circle {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>